package org.dxy.ai.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.dxy.ai.dto.ChatSessionDto;
import org.dxy.ai.service.ChatSessionService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ description: 聊天会话服务实现类
 * @ author: dxy
 * @ createTime: 2025/10/7 15:30
 */
@Slf4j
@Service
public class ChatSessionServiceImpl implements ChatSessionService {
    
    // 使用内存存储会话信息，生产环境建议使用数据库或Redis
    private final Map<String, ChatSessionDto> sessions = new ConcurrentHashMap<>();
    
    @Override
    public String createSession() {
        String sessionId = generateSessionId();
        ChatSessionDto session = new ChatSessionDto();
        session.setId(sessionId);
        session.setTitle("新对话");
        session.setCreatedAt(LocalDateTime.now());
        session.setUpdatedAt(LocalDateTime.now());
        session.setMessageCount(0);
        
        sessions.put(sessionId, session);
        log.info("创建新会话: {}", sessionId);
        return sessionId;
    }
    
    @Override
    public List<ChatSessionDto> getAllSessions() {
        List<ChatSessionDto> sessionList = new ArrayList<>(sessions.values());
        // 按更新时间倒序排列
        sessionList.sort((a, b) -> b.getUpdatedAt().compareTo(a.getUpdatedAt()));
        return sessionList;
    }
    
    @Override
    public void deleteSession(String sessionId) {
        sessions.remove(sessionId);
        log.info("删除会话: {}", sessionId);
    }
    
    @Override
    public void updateSessionTitle(String sessionId, String title) {
        ChatSessionDto session = sessions.get(sessionId);
        if (session != null) {
            session.setTitle(title);
            session.setUpdatedAt(LocalDateTime.now());
            log.info("更新会话标题: {} -> {}", sessionId, title);
        }
    }
    
    @Override
    public void incrementMessageCount(String sessionId) {
        ChatSessionDto session = sessions.get(sessionId);
        if (session != null) {
            session.setMessageCount(session.getMessageCount() + 1);
            session.setUpdatedAt(LocalDateTime.now());
        }
    }
    
    /**
     * 生成会话ID
     */
    private String generateSessionId() {
        return "session_" + System.currentTimeMillis() + "_" + UUID.randomUUID().toString().substring(0, 8);
    }
}